import React, { useState, useEffect } from "react";
import { Alert as MuiAlert, Collapse, Box } from "@mui/material";

export type AlertStatus = "success" | "info" | "warning" | "error";
export type AlertVariant = "standard" | "filled" | "outlined";

interface AlertProps {
  status: AlertStatus;
  message: string;
  variant?: AlertVariant;
  duration?: number; // 显示持续时间，单位毫秒
  onClose?: () => void; // 关闭回调
}

/**
 * 全局提示组件
 *
 * 基于 Material-UI Alert 组件的官方默认样式
 * 提供四种不同级别的消息提示：success、info、warning、error
 * 三种样式变体：standard、filled、outlined
 * @author BelovedLYC
 * @see https://mui.com/material-ui/react-alert/
 */
const Alert: React.FC<AlertProps> = ({
  status,
  message,
  variant = "standard",
  duration = 3000,
  onClose,
}) => {
  // 控制显示状态
  const [open, setOpen] = useState(true);

  // 处理关闭
  const handleClose = () => {
    setOpen(false);
    // 动画结束后调用关闭回调
    setTimeout(() => {
      if (onClose) onClose();
    }, 300); // 与 Collapse 过渡时长匹配
  };

  // 自动隐藏
  useEffect(() => {
    if (duration > 0) {
      const timer = setTimeout(handleClose, duration);
      return () => clearTimeout(timer);
    }
  }, [duration]);

  return (
    <Box
      sx={{
        position: "fixed",
        top: 24,
        left: "50%",
        transform: "translateX(-50%)",
        zIndex: 9999,
        maxWidth: "90%",
        width: "auto",
        minWidth: "320px",
      }}
    >
      <Collapse in={open}>
        <MuiAlert
          variant={variant}
          severity={status}
          onClose={handleClose}
          sx={{
            boxShadow: 2,
            borderRadius: 1,
            "& .MuiAlert-message": {
              display: "flex",
              alignItems: "center",
              padding: "6px 0",
            },
          }}
        >
          {message}
        </MuiAlert>
      </Collapse>
    </Box>
  );
};

export default Alert;
